<template>
	<view>
		<block v-if="vote">
			<u-sticky v-if="vote.fans_desc">
				<u-row customStyle="padding:5px 10px;background-color: rgba(255,255,255,.7);">
					<u-col span="2">
						<u-avatar :src="imgUrl + vote.fans_desc.avatar"></u-avatar>
					</u-col>
					<u-col span="7">
						{{vote.fans_desc.name}}
					</u-col>
					<u-col span="3">
						<u-tag text="去关注" icon="level" type="success" shape="circle" v-if="vote.fans_desc.type == 1"
							@click="img_show = true"></u-tag>
						<u-tag text="加好友" icon="weixin-fill" type="success" shape="circle"
							v-else-if="vote.fans_desc.type == 2" @click="img_show = true"></u-tag>
						<u-tag text="加入群" icon="plus-people-fill" type="success" shape="circle"
							v-else-if="vote.fans_desc.type == 3" @click="img_show = true"></u-tag>
						<u-tag text="去体验" icon="weixin-circle-fill" type="success" shape="circle"
							v-else-if="vote.fans_desc.type == 4" @click="wxapp"></u-tag>
					</u-col>
				</u-row>
			</u-sticky>

			<u-overlay :show="img_show" @click="img_show = false">
				<view style="display: flex;align-items: center;justify-content: center;height: 100%;">
					<u-image :src="imgUrl + vote.fans_desc.qr" customStyle="width:80%;heigh:80%"
						v-if="vote.fans_desc && vote.fans_desc.qr">
					</u-image>
				</view>
			</u-overlay>

			<view class="right-icon">
				<view class="right-icon-view" :style="'background-color: '+color_value"
					@click="goto('/pages/manage/manage?id='+vote_id)" v-if="user.id==vote.user_id">
					<u-icon name="grid-fill" color="#fff" size="28" label="管理" labelPos="bottom" labelColor="#fff"
						labelSize="12" space="0" top="3"></u-icon>
				</view>

			</view>

			<music :music="vote.music"></music>

			<view class="vote">
				<view class="view_common head">
					<image :src="imgUrl + vote.image" v-if="vote.image" mode="widthFix" style="width: 100%" />
					<view>{{vote.name}}</view>
					<u-count-down :time="vote.down_time" format="DD:HH:mm:ss" @change="onChange"
						v-if="vote.down_time > 0 && timeData">
						<view class="count-time">
							距离活动结束还有
							<text>{{ timeData.days }}</text>
							天
							<text>{{ timeData.hours > 10 ? timeData.hours : '0' + timeData.hours }}</text>
							时
							<text>{{ timeData.minutes }}</text>
							分
							<text>{{ timeData.seconds }}</text>
							秒
						</view>
					</u-count-down>
					<u-text text="活动已结束" align="center" lineHeight="70" v-else></u-text>
				</view>

				<view class="view_common rule">
					<view class="view_title">活动规则</view>
					<view class="rule_text"><text>开始时间</text>{{vote.start_time_text}}</view>
					<view class="rule_text"><text>结束时间</text>{{vote.end_time_text}}</view>
					<view class="rule_text">
						<text>规则</text>每天{{ vote.btn_txt||'投票' }}{{vote.day_limit_count}}次，{{ vote.day_limit_status == 1 ? '' : '不' }}可重复投给一人
					</view>
					<view class="rule_text" v-if="vote.limit_count > 0">
						<text></text>每人总可{{ vote.btn_txt||'投票' }}{{vote.limit_count}}次
					</view>

					<view class="rule_desc" v-if="vote.desc">
						<rich-text :nodes="vote.desc"></rich-text>
					</view>
				</view>

				<view class="view_common detail" v-for="(item,index) in person" :key="index">
					<view class="line">{{item.name}}</view>
					<view class="line">
						<u-tag :text="item.count+'票'" plain class="count" :color="color_value"
							:borderColor="color_value"></u-tag>
						<!-- <view class="count" :style="'background-color:'+ color_value">{{item.count}}票</view> -->
						<button :style="'background-color:'+ color_value" @click="join(item.id)">投票</button>
					</view>
				</view>

				<view style="height: 70px;"></view>

				<!-- <view class="view_common footer">
					<view class="right-icon-view"
						@click="goto('/pages/manage/manage?id='+vote_id)" v-if="user.id==vote.user_id">
						<u-icon name="grid-fill" :color="color_value" size="28" label="管理" labelPos="bottom" :labelColor="color_value"
							labelSize="12" space="0"></u-icon>
					</view>
					
					<view class="rank">
						<view class="rank-cont" :style="{'background-color':color_value}">排行榜</view>
					</view>
					<view class="log">				
						<view class="log-cont" :style="{'color':color_value,'border-color':color_value}">我投的票</view>
					</view>
				</view> -->

			</view>


			<u-popup :show="mobile_show" @close="close" mode="center" round="15">
				<view class="popup">
					<u-text text="针对国家出台的网络实名制相关要求，用户需要及时完善账户信息，并绑定手机号码。"></u-text>
					<button :class="color + '-bg'" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">点击绑定手机号</button>
				</view>
			</u-popup>

			<u-popup :show="mcaptcha_show" @close="close" mode="center" round="15">
				<view class="popup">
					<canvas class="canvas" canvas-id="canvas" id="canvas"></canvas>
					<input placeholder="请输入验证码进行投票" maxlength="4" v-model="input" type="number" class="input"
						:style="'border: 1px solid ' + color_value" />
					<button :class="color + '-bg'" @tap="verify">{{vote.btn_txt || '投票'}}</button>
				</view>
			</u-popup>

		</block>

		<!-- 投票表单 -->
		<u-popup :round="10" :closeable="true" :closeOnClickOverlay="false" :show="join_form_show" mode="center"
			@close="close">
			<view class="join_form">
				<view class="join_form_title">请提交相关资料进行投票</view>
				<u-form :model="join_form_submit" labelWidth="75px">
					<u-form-item :label="item" required v-for="(item, index) in join_form" :key="index">
						<u-input v-model="join_form_submit[item]" :placeholder="'请输入'+item" border="bottom"></u-input>
					</u-form-item>
					<button type="primary" @click="join(person_id)" class="submit">提交</button>
				</u-form>
			</view>
		</u-popup>
		<!-- 投票表单 -->

		<!-- #ifdef MP-WEIXIN -->
		<adcustom></adcustom>
		<privacy ref="privacy"></privacy>
		<!-- #endif -->
		<u-loading-page :image="system.domain+'/assets/addons/kzvote/img/loading.gif'" bgColor="#36c3e5" color="#36c3e5"
			iconSize="200" :loading="loading" v-if="system"></u-loading-page>
	</view>
</template>

<script>
	import music from '@/components/music/music.vue';
	import {
		mapGetters
	} from 'vuex';
	export default {
		computed: {
			...mapGetters({
				imgUrl: 'common/cdnurl',
				system: 'common/system',
				ad: 'common/ad',
				color: 'common/color',
				color_value: 'common/color_value',
				active: 'common/active',
			})
		},
		components: {
			music
		},
		data() {
			return {
				user: uni.getStorageSync('user'),
				vote_id: 0,
				vote: null,
				page: 1,
				keyword: '',
				has_more: true,
				group_id: -1,
				person: null,
				img_show: false,
				loading: true,
				timeData: {},
				person: {},
				person_id: 0,
				mobile_show: false,
				mcaptcha_show: false,
				ctx: '',
				verifycode: '',
				input: '',
				blue_width: 0,
				red_width: 0,
				join_form: [], //投票表单
				join_form_show: false,
				join_form_submit: {}
			};
		},
		async onLoad(options) {
			await this.$onLaunched;

			//#ifdef MP-WEIXIN
			let isPrivacySetting = await this.$refs.privacy.getPrivacySetting("showPrivacy")
			if (isPrivacySetting) {
				this.utils.wxapp_login()
			}
			let launch = uni.getLaunchOptionsSync();
			var scene = [1001, 1007, 1008, 1011, 1012, 1013, 1014, 1035, 1047, 1048, 1049, 1058, 1067, 1096, 1107]
			if (scene.indexOf(launch.scene) > -1) {
				uni.hideHomeButton()
			}
			//#endif
			if (options.scene) {
				var scene = decodeURIComponent(options.scene);
				this.vote_id = scene;
			} else {
				this.vote_id = options.vote_id;
			}
			this.ajax()


		},
		onPullDownRefresh: function() {
			this.ajax();
			uni.stopPullDownRefresh()
		},
		methods: {
			onChange(e) {
				this.timeData = e;
			},

			ajax() {
				this.http('vote/detail', {
					vote_id: this.vote_id
				}, 'get').then(res => {
					this.vote = res.data;
					if (this.vote.shield_status == 1) {
						//屏蔽流量主
						this.$store.state.common.ad = null
					} else {
						// #ifdef MP-WEIXIN
						this.adUtils.cp.load('vote_index_cp')
						// #endif
					}
					if (this.vote.join_form) {
						this.join_form = this.vote.join_form.split(',')
					}
					this.vote.down_time = this.vote.end_time * 1000 - Number(new Date());
					uni.setNavigationBarTitle({
						title: res.data.name
					});
					this.loading = false

					// #ifdef MP-WEIXIN
					uni.$u.mpShare = {
						title: this.vote.name,
						path: '/pages/vote/text?vote_id=' + this.vote.id,
						// imageUrl: '/static/img/pk.png',
					}
					// #endif
					this.utils.share({
						title: this.vote.name,
						// imgUrl: '/static/img/pk.png',
					})
					this.person = res.data.person;

				});
			},
			wxapp() {
				uni.navigateToMiniProgram({
					appId: this.vote.fans_desc.appid,
					path: this.vote.fans_desc.path,
				});
			},
			goto(url) {
				this.utils.goto(url)
			},
			close() {
				this.mobile_show = false;
				this.mcaptcha_show = false;
				this.gift_show = false;
				this.review_show = false;
				this.desc_show = false;
				this.join_form_show = false;
			},
			updated(user) {
				this.user = user
				uni.setStorageSync("user", user)
			},
			getPhoneNumber(e) {
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					uni.$u.toast('授权失败')
					return
				}
				uni.login({
					success: res => {
						var data = {
							data: e.detail.encryptedData,
							iikv: e.detail.iv,
							code: res.code
						};
						this.http('user/getPhone', data, 'post').then(res => {
							uni.setStorageSync('user', res.data.user);
							this.user = res.data.user
							uni.$u.toast('绑定成功')
							this.mobile_show = false;
						});
					}
				});
			},
			join(person_id) {
				if (!this.user.nickname || this.user.nickname.indexOf("投票用户") != -1 || !this.user.avatar) {
					this.show = true
					return false;
				}
				this.person_id = person_id;
				if (this.vote.end_time * 1000 < Number(new Date())) {
					uni.$u.toast('活动已结束')
					return;
				}
				//#ifdef MP-WEIXIN
				//验证是否需要授权手机号
				if (this.active.vote_mobile_status == 1) {
					if (this.user && !this.user.mobile) {
						this.mobile_show = true
						return;
					}
				}
				// #endif

				// 判断是否需要执行投票表单
				if (this.vote.join_form_status == 1) {
					if (this.join_form_show && this.join_form && this.join_form_submit && this.join_form.length != this
						.join_form_submit.length) {
						for (var i in this.join_form) {
							if (!this.join_form_submit[this.join_form[i]]) {
								uni.$u.toast('请填写' + this.join_form[i])
								return;
							}
						}
						this.join_form_show = false
					} else {
						this.join_form_show = true
						return;
					}
				}

				this.ctx = uni.createCanvasContext('canvas', this);
				if (this.vote.verify_status == 1) {
					this.refresh();
					this.mcaptcha_show = true;
					return;
				}
				this.submit()
			},
			verify() {
				if (this.verifycode == parseInt(this.input)) {
					this.mcaptcha_show = false;
					this.verifycode = '';
					this.input = '';
					this.submit();
				} else {
					uni.$u.toast('验证码错误，请重新输入')
					this.refresh();
				}
			},

			submit() {
				let send = false;
				// #ifdef MP-WEIXIN
				let tmplIds = ''
				if (this.subscription && this.subscription != null && this.subscription != 'null') {
					tmplIds = this.subscription.toupiaojieguo
				}
				uni.requestSubscribeMessage({
					tmplIds: [tmplIds],
					complete: res => {
						if (res[tmplIds] == 'accept') {
							send = true;
						}
						// #endif
						this.http('person/vote', {
							vote_id: this.vote.id,
							person_id: this.person_id,
							join_form: this.join_form_submit,
							send: send,
						}, 'post').then(res => {
							if (res.code) {
								this.join_form_submit = {}
								this.ajax()
								uni.$u.toast(res.msg)
							} else {
								uni.showModal({
									title: '提示',
									content: res.msg,
									showCancel: false,
									success(res) {

									}
								})
							}
						});
						// #ifdef MP-WEIXIN
					}
				});
				// #endif
			},
			refresh() {
				var randomNum = Math.random();
				var code = parseInt(randomNum * 9000 + 1000) + '';
				this.verifycode = code;
				this.ctx.clearRect(0, 0, 120, 40);
				this.ctx.setTextBaseline('middle');
				this.ctx.setFillStyle(this.randomColor(180, 240));
				this.ctx.fillRect(0, 0, 120, 40);
				let arr = code.split('');
				if (arr.length === 0) {
					arr = ['e', 'r', 'r', 'o', 'r'];
				}
				let offsetLeft = (120 * 0.6) / (arr.length - 1);
				let marginLeft = 120 * 0.2;
				arr.forEach((item, index) => {
					this.ctx.setFillStyle(this.randomColor(0, 180));
					let size = this.randomNum(24, (40 * 3) / 4);
					this.ctx.setFontSize(size);
					let dis = offsetLeft * index + marginLeft - size * 0.3;
					let deg = this.randomNum(-30, 30);
					this.ctx.translate(dis, 20);
					this.ctx.rotate((deg * Math.PI) / 180);
					this.ctx.fillText(item, 0, 0);
					this.ctx.rotate((-deg * Math.PI) / 180);
					this.ctx.translate(-dis, -20);
				});
				this.input = '';
				setTimeout(() => {
					this.ctx.draw();
				}, 200);
			},
			randomNum(min, max) {
				return Math.floor(Math.random() * (max - min) + min);
			},
			randomColor(min, max) {
				let r = this.randomNum(min, max);
				let g = this.randomNum(min, max);
				let b = this.randomNum(min, max);
				return 'rgb(' + r + ',' + g + ',' + b + ')';
			}
		}
	};
</script>

<style lang="scss">
	.right-icon {
		width: 50px;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		position: fixed;
		bottom: 80px;
		right: 15px;
		z-index: 99;
	
		.right-icon-view {
			width: 50px;
			height: 50px;
			border-radius: 50%;
		}
	}
	
	.footer {
		display: flex;
		margin-top: 10px;
		height: 60px;
		line-height: 60px;
		text-align: center;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding-top: 5px;

		.right-icon-view {
			width: 50px;
			height: 50px;
			border-radius: 50%;
			display: inline-block;
			margin-top: 5px;
		}

		.rank {
			flex: 2;
			padding-top: 5px;
			color: #fff;

			.rank-cont {
				width: 100px;
				height: 40px;
				line-height: 40px;
				margin: 0 auto;
				border-radius: 5px;
			}
		}

		.log {
			flex: 2;
			padding-top: 5px;

			.log-cont {
				width: 100px;
				height: 40px;
				line-height: 40px;
				margin: 0 auto;
				border: 1px solid;
				border-radius: 5px;
			}
		}
	}


	.vote {
		width: 95%;
		margin: 0 auto;
		padding-bottom: 20px;
	}

	.view_common {
		background-color: #fff;
		border-radius: 5px;
		padding-bottom: 10px;
		box-shadow: x-shadow 0 10px 10px rgba(0, 0, 0, .2);
	}

	.view_title {
		height: 45px;
		line-height: 45px;
		text-align: center;
		border-bottom: 1px solid #ededed;
	}

	.head {
		view {
			height: 35px;
			line-height: 35px;
			text-indent: 10px;

			.count-time text {
				color: #a1d774;
				padding: 0 3px;
			}
		}
	}

	.detail {
		margin-top: 10px;
		padding: 0px 10px;

		.line {
			height: 40px;
			line-height: 40px;

			view {
				height: 30px;
				line-height: 30px;
				font-size: 14px;
				display: inline-block;
			}

			.count {
				float: left;
			}

			button {
				height: 30px;
				line-height: 30px;
				font-size: 14px;
				display: inline-block;
				color: #fff;
				width: 100px;
				float: right;
			}
		}
	}

	.rule {
		margin-top: 10px;

		.rule_text {
			height: 30px;
			line-height: 30px;
			text-indent: 10px;

			text {
				font-weight: bold;
				width: 90px;
				display: inline-block;
			}
		}

		.rule_desc {
			border-top: 1px solid #ededed;
			margin-top: 20px;
			padding: 10px;
		}
	}
</style>
